const { Service } = require('egg')
const { encodeInp } = require('../utils/encryption')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this// ! cokie未正确完成，感觉没问题
      const { sid, pwd } = ctx.data
      const apiUrl = 'https://oauth2.hunnu.edu.cn/token?e=e30%3D'
      const res = await ctx.curl(apiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const token1 = JSON.parse(res.data.toString())// 获取token
      const Authorization = `Bearer ${token1.data.token}`// 构造Authorization
      // 构造t
      const t = {
        client_id: '2ba6010a-f4fc-49f5-a804-45c603608d04',
        redirect_uri: 'https://jwglnew.hunnu.edu.cn/eams/oauth2-login',
        state: 'hunnu-jw?backUrl=/loginExt.action',
        mode: 'password',
        identity: sid,
        password: pwd,
        address: '',
        validcode: '',
      }
      const e = encodeInp(JSON.stringify(t))
      const apiUrl2 = 'https://oauth2.hunnu.edu.cn/login'
      const res2 = await ctx.curl(apiUrl2, {
        method: 'POST',
        data: {
          e,
        },
        headers: {
          Authorization,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const messages = JSON.parse(res2.data.toString())// 获取messages
      // 判断用户名是否成功登录
      if (messages.message === '') {
        // 第一层地址
        const P3 = JSON.parse(res2.data.toString())
        // console.log('P3.data.transfer', P3.data.transfer);
        const res3 = await ctx.curl(P3.data.transfer, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          },
        })

        // 第二层地址
        const P4 = `https://oauth2.hunnu.edu.cn${res3.headers.location}`
        const setCookie1 = res3.headers['set-cookie'][0].split(';')[0]
        const res4 = await ctx.curl(P4, {
          method: 'GET',
          headers: {
            cookie: setCookie1,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          },
        })

        // 第三层地址
        const P5 = res4.headers.location
        // const set_cookie2 = res4.headers['set-cookie'][0].split(';')[0];//! 不知取到后干了啥
        const res5 = await ctx.curl(P5, {
          method: 'GET',
          headers: {
          // cookie: set_cookie2,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          },
        })
        // console.log('res5', res5);// 返回值少了JSESSIONID，GSESSIONID

        // 第四层地址
        const P6 = res5.headers.location
        const setCookie3 = res5.headers['set-cookie'].map((ee) => ee.split(';')[0])// 取到后可用可不用
        const res6 = await ctx.curl(P6, {
          method: 'GET',
          headers: {
            cookie: setCookie3, // 用则返回JSESSIONID+GSESSIONID，不用则返回JSESSIONID+GSESSIONID+SERVERNAME
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          },
        })

        // 第五层地址
        const P7 = res6.headers.location
        // console.log('P7', P7);
        const setCookie4 = res6.headers['set-cookie'].map((ee) => ee.split(';')[0])
        // console.log('set_cookie4', set_cookie4);
        const setCookie = ([...setCookie4, ...setCookie3]).join('; ')
        // console.log('A', A);
        // const setCookie = A.join('; ');
        // console.log('setCookie', setCookie);
        const res7 = await ctx.curl(P7, {
          method: 'GET',
          headers: {
            cookie: setCookie,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          },
        })
        // console.log('res7', res7);
        const status = res7.status === 200 ? 302 : 500
        // const P8 = res7.data.toString();
        // console.log('P8', P8);
        return { setCookie, status }
      }

      // 登录未通过
      console.log('messages.message', messages.message)
      const status = res2.status
      return { setCookie: '', status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
